package com.zwd.cases.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * @Description PDF常用方法封装工具类
 * @Author zhengwd
 * @Date 2022/5/13 10:47
 **/
public class PdfUtil {

    public static void main(String[] args) {
        try {
            // 生成PDF测试
//            createPdfFromHtmlTest();
            // 下载网络PDF文件测试
            downloadPdfWwTest();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 外网PDF文件下载测试
     * @throws IOException
     */
    private static void downloadPdfWwTest() throws IOException {
        // 外网PDF路径（该地址为个人服务器文件地址，仅供测试使用）
        String urlStr = "http://106.13.205.23:8080/pdf/%E6%B5%8B%E8%AF%95pad.pdf";
        // 存储PDF文件名
        String fileName = "a.pdf";
        // PDF存储位置
        String savePath = "C:\\Users\\86178\\Desktop";
        downLoadByUrl(urlStr, fileName, savePath);
    }

    /**
     * 生成PDF文件-测试
     * @throws Exception
     */
    private static void createPdfFromHtmlTest() throws Exception {
        // 文件存储目标路径（改成你的路径+文件名）
        String path = "C:\\Users\\86178\\Desktop\\测试pad.pdf";

        // 测试用，获取一张项目图片（可不要）
        String contextPath = getContextPath();
        contextPath = contextPath.replace("target/test-classes/", "");
        String imgPath = contextPath + "src/test/java/com/zwd/cases/demo/img/exception/testExceptionImg.jpg";
        // 输出：/D:/workspace/projects/cases/src/test/java/com/zwd/cases/demo/img/exception/testExceptionImg.jpg
        System.out.println(imgPath);

        // PDF排版html信息
        String htmlString = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "  <head>\n" +
                "    <meta charset=\"utf-8\"/>\n" +
                "    <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"/>\n" +
                "    <title>vue-test</title>\n" +
                "  </head>\n" +
                "  <body>\n" +
                "    <div id=\"app\"></div>\n" +
                "    <!-- built files will be auto injected -->\n" +
                "    <h3>Zwd PDF 生成测试~</h3>\n" +
                "    <img src='"+ imgPath +"' />\n" +
                "  </body>\n" +
                "</html>";
        PdfUtil.pdfProcess(htmlString, path);
    }

    /**
     * HTML文件内容生成PDF文件核心方法
     * @param htmlString html文件格式字符串
     * @param pdfFileAimPath PDF文件生成路径
     * @throws Exception
     */
    public static void pdfProcess(String htmlString, String pdfFileAimPath) throws Exception {
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFileAimPath));
        document.open();
        XMLWorkerHelper helper = XMLWorkerHelper.getInstance();
        InputStream inputStream = null;
        helper.parseXHtml(pdfWriter, document, new ByteArrayInputStream(htmlString.getBytes("utf-8")), inputStream, Charset.forName("UTF-8"));
        document.close();
        System.out.println("PDF文件生成成功");
    }

    /**
     * 获取上下文路径
     * @return
     */
    private static String getContextPath() {
        return PdfUtil.class.getResource("/").getPath();
    }

    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void downLoadByUrl(String urlStr, String fileName, String savePath)
            throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置超时间为3秒
        conn.setConnectTimeout(5 * 1000);
        // 防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        // 得到输入流
        InputStream inputStream = conn.getInputStream();
        // 获取自己数组
        byte[] getData = readInputStream(inputStream);
        // 文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        System.out.println("文件:" + url + "，下载到 " + savePath + "成功~");
    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream)
            throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}